<template>
  <div>
    <crumbs secondTitle="商品管理" thirdTitle="分类参数"></crumbs>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <!-- change-on-select -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            change-on-select
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tap 页面区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTapClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="controlSwitch"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环 tag 标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="callChildren(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteEditDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="controlSwitch"
            >添加属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyTableDate" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环 tag 标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="callChildren(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteEditDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性对话框 -->
    <!-- 修改参数的对话框 -->
    <params-dialog
      ref="addFormRef"
      :cateId="cateId"
      :attr_id.sync="attr_id"
      :activeName="activeName"
      :isDynamicSwitch.sync="isDynamicSwitch"
      @getUpdateData="getUpdateData"
    />
  </div>
</template>
<script>
import {
  getCateList,
  getParameterList,
  editorAddParams,
  editorDeleteParams
} from '@/api/params'
import ParamsDialog from './paramsDialog.vue'
export default {
  components: {
    ParamsDialog
  },
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择框 双向绑定的数组
      selectedCateKeys: [],
      // tap 默认选择
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态参数的数据
      onlyTableDate: [],
      // 控制添加参数对话框的显示与隐藏
      isDynamicSwitch: false,
      // 添加参数/属性表单的数据对象
      addForm: {
        attr_name: ''
      },
      // 添加参数/属性表单的的规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改对话框的显示与隐藏
      editDialogVisible: false,
      // 修改的表单对象
      editForm: {},
      // 修改参数/属性表单的的规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      attr_id: null
    }
  },
  methods: {
    // 父组件调用子组件的方法
    callChildren(id) {
      this.attr_id = id
      this.isDynamicSwitch = true
      this.$refs.addFormRef.editCall(id)
    },
    // 自组件通知父级来更改
    getUpdateData() {
      this.getParamsData()
    },
    // 级联选择框 变化会触发这个函数
    handleChange() {
      this.getParamsData()
    },
    async loadCateList() {
      const res = await getCateList(this.queryInfo)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      // 将数据列表赋值给 cateListnf
      this.cateList = res.data
    },
    // tap栏 发生变化 会触发这个函数
    handleTapClick() {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const res = await getParameterList(this.cateId, this.activeName)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框显示的值
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      }
      if (this.activeName === 'only') {
        this.onlyTableDate = res.data
      }
    },
    // 控制添加参数对话框的显示与隐藏
    controlSwitch() {
      this.isDynamicSwitch = true
    },
    // 删除参数/属性
    async deleteEditDialog(id) {
      try {
        await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await editorDeleteParams(this.cateId, id)
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
          this.getParamsData()
        } else {
          this.$message.error('删除失败')
        }
      } catch (error) {
        this.$message.info('取消删除')
      }
    },
    // 输入的文本框的监听事件 ( 失去焦点/摁下 Enter ) 都会触发
    async handleInputConfirm(row) {
      // 判断 input 值是否合格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发送请求 保存数据
      this.saveAttrVals(row)
    },
    // 对 attr_vals 的操作保存
    async saveAttrVals(row) {
      try {
        const res = await editorAddParams({
          id: this.cateId,
          attrId: row.attr_id,
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        if (res.meta.status === 200) {
          this.$message.success('参数跟新成功')
        }
      } catch (error) {
        this.$message.error('参数跟新失败')
      }
    },
    // 删除参数
    async handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    // 点击按钮 切换文本框
    showInput(row) {
      row.inputVisible = true
      // 自动获取文本框的焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  mounted() {
    this.loadCateList()
  },
  computed: {
    // 通过判断数组长度 动态控制 :disadled
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
